<template>
  <div class="enrollment-management">
    <!-- 页面标题 -->
    <div class="page-title">
      <h1>选课信息管理</h1>
    </div>

    <!-- 搜索条件 -->
    <div class="search-conditions">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item v-if="!isStudent" label="学号">
          <el-input
            v-model="searchForm.studentId"
            placeholder="请输入学号"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="课程编号">
          <el-input
            v-model="searchForm.courseCode"
            placeholder="请输入课程编号"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="学期">
          <el-select
            v-model="searchForm.semester"
            placeholder="请选择学期"
            clearable
            style="width: 150px"
          >
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
            <el-option label="2026春季" value="2026春季" />
            <el-option label="2026秋季" value="2026秋季" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="已选" value="ENROLLED" />
            <el-option label="已退" value="DROPPED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button 
        v-if="canCreate('enrollment-management')" 
        type="primary" 
        @click="showAddDialog = true"
      >
        <el-icon><Plus /></el-icon>
        学生选课
      </el-button>
    </div>

    <!-- 选课信息列表 -->
    <div class="enrollment-list">
      <el-table
        :data="enrollmentList"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="studentName" label="姓名" width="100" />
        <el-table-column prop="courseCode" label="课程编号" width="120" />
        <el-table-column prop="courseName" label="课程名称" width="200" />
        <el-table-column prop="semester" label="学期" width="100" />
        <el-table-column prop="enrollmentDate" label="选课时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.enrollmentDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === 'ENROLLED' && canDelete('enrollment-management')" 
              type="warning" 
              size="small" 
              @click="handleDropCourse(row)"
            >
              退课
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <span class="total-info">共{{ pagination.total }}条记录</span>
      </div>
    </div>

    <!-- 添加选课对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="添加选课"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="enrollmentFormRef"
        :model="enrollmentForm"
        :rules="enrollmentRules"
        label-width="80px"
      >
        <el-form-item v-if="!isStudent" label="学生" prop="studentId">
          <el-select
            v-model="enrollmentForm.studentId"
            placeholder="请选择学生"
            style="width: 100%"
            filterable
            @change="handleStudentChange"
          >
            <el-option
              v-for="student in studentOptions"
              :key="student.studentId"
              :label="`${student.name} (${student.studentId})`"
              :value="student.studentId"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-else label="学生">
          <el-input
            :value="`${store.state.user.userInfo?.realName || store.state.user.userInfo?.username || ''} (${currentStudentId})`"
            disabled
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select
            v-model="enrollmentForm.courseId"
            placeholder="请选择课程"
            style="width: 100%"
            filterable
            @change="handleCourseChange"
          >
            <el-option
              v-for="course in courseOptions"
              :key="course.courseId"
              :label="`${course.courseName} (${course.courseId})`"
              :value="course.courseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学期" prop="semester">
          <el-select v-model="enrollmentForm.semester" placeholder="请选择学期" style="width: 100%">
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
            <el-option label="2026春季" value="2026春季" />
            <el-option label="2026秋季" value="2026秋季" />
          </el-select>
        </el-form-item>
        <el-form-item label="选课时间" prop="enrollmentDate">
          <el-date-picker
            v-model="enrollmentForm.enrollmentDate"
            type="date"
            placeholder="选择选课时间"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          添加
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { getEnrollmentList, selectCourse, dropCourse, getStudentOptions, getCourseOptions } from '@/api/enrollment'
import { canCreate, canDelete } from '@/utils/permission'
import store from '@/store'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const showAddDialog = ref(false)
const enrollmentFormRef = ref()
const selectedRows = ref([])

// 计算属性：当前用户角色和学号
const currentUserRole = computed(() => {
  const role = store.state.user.userInfo?.role || ''
  console.log('当前用户角色:', role)
  return role
})

const currentStudentId = computed(() => {
  const studentId = store.state.user.userInfo?.relatedId || ''
  console.log('当前学生学号:', studentId)
  return studentId
})

// 计算属性：是否为学生角色
const isStudent = computed(() => {
  const role = currentUserRole.value
  const isStudentRole = role === '学生' || role === 'STUDENT'
  console.log('是否为学生角色:', isStudentRole, '角色:', role)
  return isStudentRole
})

// 搜索表单
const searchForm = reactive({
  studentId: '',
  courseCode: '',
  semester: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 选课列表
const enrollmentList = ref([])

// 学生选项
const studentOptions = ref([])

// 课程选项
const courseOptions = ref([])

// 选课表单
const enrollmentForm = reactive({
  studentId: '',
  courseId: '',
  semester: '',
  enrollmentDate: ''
})

// 表单验证规则
const enrollmentRules = computed(() => {
  const rules = {
    courseId: [
      { required: true, message: '请选择课程', trigger: 'change' }
    ],
    semester: [
      { required: true, message: '请选择学期', trigger: 'change' }
    ],
    enrollmentDate: [
      { required: true, message: '请选择选课时间', trigger: 'change' }
    ]
  }
  
  // 非学生角色需要验证学生选择
  if (!isStudent.value) {
    rules.studentId = [
      { required: true, message: '请选择学生', trigger: 'change' }
    ]
  }
  
  return rules
})

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'ENROLLED': 'success',
    'DROPPED': 'warning',
    'COMPLETED': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'ENROLLED': '已选课',
    'DROPPED': '已退课',
    'COMPLETED': '已完成'
  }
  return statusMap[status] || '未知'
}

// 格式化日期，只显示到天
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 获取选课列表
const getEnrollmentListData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage - 1, // 后端从0开始
      size: pagination.pageSize,
      studentId: searchForm.studentId || undefined,
      courseId: searchForm.courseCode || undefined,
      semester: searchForm.semester || undefined,
      status: searchForm.status || undefined
    }
    
    // 学生角色强制设置学号参数，确保只显示自己的数据
    if (isStudent.value) {
      params.studentId = currentStudentId.value
      console.log('学生角色，强制设置学号参数:', params.studentId)
    }
    
    console.log('请求参数:', params)
    const response = await getEnrollmentList(params)
    if (response.code === 200) {
      enrollmentList.value = response.data.content || []
      pagination.total = response.data.totalElements || 0
      console.log('选课列表数据:', enrollmentList.value)
    } else {
      ElMessage.error(response.message || '获取选课列表失败')
    }
  } catch (error) {
    console.error('获取选课列表失败:', error)
    ElMessage.error('获取选课列表失败')
  } finally {
    loading.value = false
  }
}

// 获取学生选项
const getStudentOptionsData = async () => {
  try {
    const response = await getStudentOptions()
    if (response.code === 200) {
      studentOptions.value = response.data.content || []
    } else {
      ElMessage.error(response.message || '获取学生列表失败')
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取学生列表失败')
  }
}

// 获取课程选项
const getCourseOptionsData = async () => {
  try {
    const response = await getCourseOptions()
    if (response.code === 200) {
      courseOptions.value = response.data.content || []
    } else {
      ElMessage.error(response.message || '获取课程列表失败')
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  }
}

// 学生选择改变
const handleStudentChange = (studentId) => {
  const student = studentOptions.value.find(s => s.studentId === studentId)
  if (student) {
    enrollmentForm.studentName = student.name
  }
}

// 课程选择改变
const handleCourseChange = (courseId) => {
  const course = courseOptions.value.find(c => c.courseId === courseId)
  if (course) {
    enrollmentForm.courseName = course.courseName
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getEnrollmentListData()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.currentPage = 1
  getEnrollmentListData()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  getEnrollmentListData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getEnrollmentListData()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 退课
const handleDropCourse = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要退选课程 "${row.courseName}" 吗？`,
      '确认退课',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await dropCourse({
      studentId: row.studentId,
      courseId: row.courseId,
      semester: row.semester
    })
    
    if (response.code === 200) {
      ElMessage.success('退课成功')
      getEnrollmentListData()
    } else {
      ElMessage.error(response.message || '退课失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退课失败:', error)
      ElMessage.error('退课失败')
    }
  }
}

// 删除选课记录
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选课记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟删除操作
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('删除成功')
    getEnrollmentList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await enrollmentFormRef.value.validate()
    
    submitting.value = true
    
    const enrollmentData = {
      studentId: enrollmentForm.studentId,
      courseId: enrollmentForm.courseId,
      semester: enrollmentForm.semester,
      enrollmentDate: enrollmentForm.enrollmentDate
    }
    
    // 学生角色只能为自己选课
    if (isStudent.value) {
      enrollmentData.studentId = currentStudentId.value
      console.log('学生角色选课，强制设置学号:', enrollmentData.studentId)
    }
    
    console.log('选课数据:', enrollmentData)
    const response = await selectCourse(enrollmentData)
    if (response.code === 200) {
      ElMessage.success('选课成功')
      showAddDialog.value = false
      getEnrollmentListData()
    } else {
      ElMessage.error(response.message || '选课失败')
    }
  } catch (error) {
    console.error('选课失败:', error)
    ElMessage.error('选课失败')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(enrollmentForm, {
    studentId: '',
    courseId: '',
    semester: '',
    enrollmentDate: ''
  })
  enrollmentFormRef.value?.resetFields()
}

// 组件挂载时获取数据
onMounted(() => {
  console.log('组件挂载 - 用户信息:', store.state.user.userInfo)
  console.log('组件挂载 - 是否为学生:', isStudent.value)
  console.log('组件挂载 - 当前学号:', currentStudentId.value)
  
  getEnrollmentListData()
  // 非学生角色才需要获取学生选项
  if (!isStudent.value) {
    getStudentOptionsData()
  }
  getCourseOptionsData()
  
  // 学生角色自动设置学号
  if (isStudent.value) {
    enrollmentForm.studentId = currentStudentId.value
    console.log('学生角色自动设置学号:', enrollmentForm.studentId)
  }
})
</script>

<style lang="scss" scoped>
.enrollment-management {
  .page-title {
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin: 0;
    }
  }
  
  .search-conditions {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .search-form {
      .el-form-item {
        margin-bottom: 0;
        margin-right: 16px;
      }
    }
  }
  
  .action-bar {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
  }
  
  .enrollment-list {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .el-table {
      margin-bottom: 16px;
      
      :deep(.el-table__header) {
        th {
          background: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }
      
      :deep(.el-table__row) {
        &:hover {
          background: #f8f9ff;
        }
      }
    }
    
    .pagination-container {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .total-info {
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .enrollment-management {
    .search-conditions {
      .search-form {
        .el-form-item {
          margin-bottom: 16px;
          margin-right: 0;
        }
      }
    }
    
    .action-bar {
      flex-direction: column;
      
      .el-button {
        width: 100%;
      }
    }
    
    .enrollment-list {
      padding: 16px;
      overflow-x: auto;
    }
  }
}
</style>
